﻿using Dapper;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using OMG.Fill.Mulberry.Model;
using OMG.Fill.Mulberry.Model.Ent;
using ProjectShare;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace OMG.Fill.Mulberry.Service
{
    /// <summary>
    /// 蚕丝绸企业信息调查表通用操作类
    /// </summary>
    public class MulSilkCompanyServices:MulSilkCompanys
    {
        DictServices dict = new DictServices();
        public Pager<List<MulSilkCompanyEntity>> GetPageList(MulSilkCompanyQuery query)
        {
            Pager<List<MulSilkCompanyEntity>> obj = new Pager<List<MulSilkCompanyEntity>>();
            var paramlist = new DynamicParameters();
            string strWhereSql = "";//from 表在下面，需完善其他查询条件在这里接的写，格式为："and xxx=@xxx空格,如下注释部分代码所示："
            //if (!string.IsNullOrEmpty(query.GroupCode))
            //{
            //  strWhereSql += "and GroupCode = @GroupCode ";
            //  paramlist.Add("GroupCode", query.GroupCode);
            //}
            string strFromSql = "from dbo.MulSilkCompany where 1=1 " + strWhereSql;
            string strTotal = "select count(1)" + strFromSql + strWhereSql;
            string strOrderSql = "";//自定义完成order by语句
            string strSql = @"select * from (select *,ROW_NUMBER() over (order by ID ) as RowNumber " + strFromSql + ") as t ";
            strSql += "where t.RowNumber between  @minRow and @maxRow" + strOrderSql;
            paramlist.Add("minRow", query.MinRow);
            paramlist.Add("maxRow", query.MaxRow);
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    obj.rows = dbCon.Query<MulSilkCompanyEntity>(strSql,paramlist).ToList();
                    obj.total = dbCon.Query<int>(strTotal,paramlist).FirstOrDefault();
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "获取成功！";
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("获取蚕丝绸企业信息调查表分页列表失败", ex);
                return obj;
            }
        }
        /// <summary>
        /// 获取指定对象
        /// </summary>
        public ResResult<List<MulSilkCompanyEntity>> GetList(string ReportId)
        {
            ResResult<List<MulSilkCompanyEntity>> obj = new ResResult<List<MulSilkCompanyEntity>>();
            MulSilkCompanyEntity model = new MulSilkCompanyEntity();
            if (CheckRepCount(ReportId))
            {
                model.ReportId = ReportId;
                model.CompanyName = "";
                model.Remark = "";
                if (AddInfo(model).status > 0)
                {
                    obj.model = new List<MulSilkCompanyEntity>();
                    obj.model.Add(model);
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "获取成功！";
                }
            }
            else
            {
                string strSql = @"select * from dbo.MulSilkCompany where ReportId = @ReportId";
                try
                {
                    using (var dbCon = ConnectFactory.GetOpenConnection())
                    {
                        obj.model = dbCon.Query<MulSilkCompanyEntity>(strSql, new { ReportId = ReportId }).ToList();
                        obj.status = DefaultKey.SuccessResult;
                        obj.message = "获取成功！";
                        dbCon.Dispose();//数据库连接释放
                    }
                }
                catch (Exception ex)
                {
                    obj.status = DefaultKey.ErrorResult;
                    obj.message = ex.ToString().Trim();
                    LogHelper.ErrorLog("获取表11茧丝绸企业信息调查表MulSilkCompany对象信息失败", ex);

                }
            }
            return obj;
        }
        /// <summary>
        /// 判定是否生成过报表
        /// </summary>
        /// <param name="reportId"></param>
        /// <returns>没生成过true,否则false</returns>
        public bool CheckRepCount(string reportId)
        {
            string strSql = @"select count(1) from dbo.MulSilkCompany where ReportId=@ReportId";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    //为0，没生成过true,否则false
                    return dbCon.Query<int>(strSql, new { ReportId = reportId }).FirstOrDefault() == 0 ? true : false;
                }
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog("判断是否生成过表11茧丝绸企业信息调查表MulSilkCompany失败", ex);
                return false;
            }
        }
        public ResResult<int> AddInfo(List<MulSilkCompanyEntity> list)
        {
            ResResult<int> obj = new ResResult<int>();
            string strSql = @"INSERT INTO dbo.MulSilkCompany";
            strSql += "(";
            strSql += "Id,";
            strSql += "ReportId,";
            strSql += "CompanyName,";
            strSql += "GDZC,";
            strSql += "CSNL,";
            strSql += "BCSCL,";
            strSql += "SCCL,";
            strSql += "NJGCSB,";
            strSql += "Other,";
            strSql += "Remark)";
            strSql += " values(";
            strSql += "@Id,";
            strSql += "@ReportId,";
            strSql += "@CompanyName,";
            strSql += "@GDZC,";
            strSql += "@CSNL,";
            strSql += "@BCSCL,";
            strSql += "@SCCL,";
            strSql += "@NJGCSB,";
            strSql += "@Other,";
            strSql += "@Remark)";
            using (var dbCon = ConnectFactory.GetOpenConnection())
            {
                var trans = dbCon.BeginTransaction();
                try
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        list[i].ID = CustomFun.GetGuid();
                    }

                    string strDel = "delete from dbo.MulSilkCompany where ReportId=@ReportId";
                    dbCon.Execute(strDel, new { ReportId = list[0].ReportId }, trans);
                    int result = dbCon.Execute(strSql, list, trans);
                    string strRep = "update dbo.T_Report set Status='2',UpdateTime=@UpdateTime where Id=@ReportId";
                    dbCon.Execute(strRep, new { ReportId = list[0].ReportId, UpdateTime = DateTime.Now }, trans);
                    //提交事务
                    trans.Commit();
                    obj.model = result;
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "更新成功！";
                    dbCon.Dispose();//数据库连接释放
                    return obj;

                }
                catch (Exception ex)
                {
                    obj.status = DefaultKey.ErrorResult;
                    obj.message = ex.ToString().Trim();
                    LogHelper.ErrorLog("新增表11茧丝绸企业信息调查表MulSilkCompany对象信息失败", ex);
                    return obj;
                }
            }
        }
        /// <summary>
        /// 读取导入的Excel数据
        /// </summary>
        /// <param name="pathName">导入文件路径</param>
        /// <param name="fileSuffix">文件后缀</param>
        /// <param name="sheetName">sheet名称</param>
        /// <param name="startRow">从第几行开始读取数据</param>
        /// <returns></returns>
        public List<MulSilkCompanyModel> ExcelToModel(string pathName, string fileSuffix, string sheetName, int startRow)
        {

            IWorkbook workbook = null;
            ISheet sheet = null;
            List<MulSilkCompanyModel> list = new List<MulSilkCompanyModel>();
            FileStream fs = new FileStream(pathName, FileMode.Open, FileAccess.Read);
            switch (fileSuffix)
            {
                case ".xls":
                    workbook = new HSSFWorkbook(fs);
                    break;
                case ".xlsx":
                    workbook = new XSSFWorkbook(fs);
                    break;
                default:
                    workbook = new HSSFWorkbook(fs);
                    break;
            }
            if (!string.IsNullOrEmpty(sheetName))
            {
                sheet = workbook.GetSheet(sheetName);
                if (sheet == null) //如果没有找到指定的sheetName对应的sheet，则尝试获取第一个sheet
                {
                    sheet = workbook.GetSheetAt(0);
                }
            }
            else
            {
                sheet = workbook.GetSheetAt(0);
            }
            if (sheet != null)
            {
                //获取有数据的行数
                int rowCount = 0;
                for (int i = startRow; i <= sheet.LastRowNum; i++)
                {
                    IRow row = sheet.GetRow(i);
                    if (row != null)
                    {
                        rowCount = sheet.GetRow(i).RowNum;
                    }
                    else
                    {
                        break;
                    }
                }
                for (int i = startRow; i <= rowCount; i++)
                {
                    IRow row = sheet.GetRow(i);
                    MulSilkCompanyModel model = new MulSilkCompanyModel();
                    model.year = row.GetCell(0).ToString();
                    if (row.GetCell(1) != null && row.GetCell(1).ToString() != "")
                    {
                        model.CompanyName = row.GetCell(1).ToString();
                    }
                    else
                    {
                        model.CompanyName = null;
                    }
                    if (row.GetCell(2) != null && row.GetCell(2).ToString() != "")
                    {
                        model.GDZC = decimal.Parse(row.GetCell(2).ToString());
                    }
                    else
                    {
                        model.GDZC = null;
                    }
                    if (row.GetCell(3) != null && row.GetCell(3).ToString() != "")
                    {
                        model.CSNL = decimal.Parse(row.GetCell(3).ToString());
                    }
                    else
                    {
                        model.CSNL = null;
                    }
                    if (row.GetCell(4) != null && row.GetCell(4).ToString() != "")
                    {
                        model.BCSCL = decimal.Parse(row.GetCell(4).ToString());
                    }
                    else
                    {
                        model.BCSCL = null;
                    }
                    if (row.GetCell(5) != null && row.GetCell(5).ToString() != "")
                    {
                        model.SCCL = decimal.Parse(row.GetCell(5).ToString());
                    }
                    else
                    {
                        model.SCCL = null;
                    }
                    if (row.GetCell(6) != null && row.GetCell(6).ToString() != "")
                    {
                        model.NJGCSB = decimal.Parse(row.GetCell(6).ToString());
                    }
                    else
                    {
                        model.NJGCSB = null;
                    }
                    if (row.GetCell(7) != null && row.GetCell(7).ToString() != "")
                    {
                        model.Other = row.GetCell(7).ToString();
                    }
                    else
                    {
                        model.Other = null;
                    }
                    if (row.GetCell(8) != null && row.GetCell(8).ToString() != "")
                    {
                        model.Remark = row.GetCell(5).ToString();
                    }
                    else
                    {
                        model.Remark = null;
                    }
                    list.Add(model);
                }
            }
            return list;
        }
        /// <summary>
        /// 添加
        /// </summary>
        public virtual ResResult<int> AddInfo(MulSilkCompanyModel model)
        {
            ResResult<int> obj = new ResResult<int>();
            string strSql = @"INSERT INTO dbo.MulSilkCompany";
            strSql += "(";
            strSql += "Id,";
            strSql += "ReportId,";
            strSql += "CompanyName,";
            strSql += "GDZC,";
            strSql += "CSNL,";
            strSql += "BCSCL,";
            strSql += "SCCL,";
            strSql += "NJGCSB,";
            strSql += "Other,";
            strSql += "Remark)";
            strSql += " values(";
            strSql += "@Id,";
            strSql += "@ReportId,";
            strSql += "@CompanyName,";
            strSql += "@GDZC,";
            strSql += "@CSNL,";
            strSql += "@BCSCL,";
            strSql += "@SCCL,";
            strSql += "@NJGCSB,";
            strSql += "@Other,";
            strSql += "@Remark)";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    model.ID = CustomFun.GetGuid();
                    int result = dbCon.Execute(strSql, model);
                    if (result > 0)
                    {
                        obj.model = result;
                        obj.status = DefaultKey.SuccessResult;
                        obj.message = "添加成功！";
                    }
                    else
                    {
                        obj.model = result;
                        obj.status = DefaultKey.InfoResult;
                        obj.message = "添加失败！数量为:" + result;
                    }
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("新增表11茧丝绸企业信息调查表MulSilkCompany对象信息失败", ex);
                return obj;
            }
        }
        /// <summary>
        /// 修改
        /// </summary>
        public virtual ResResult<int> UpdateInfo(MulSilkCompanyModel model)
        {
            ResResult<int> obj = new ResResult<int>();
            string strSql = @"UPDATE dbo.MulSilkCompany set ";
            strSql += "CompanyName = @CompanyName,";
            strSql += "GDZC = @GDZC,";
            strSql += "CSNL = @CSNL,";
            strSql += "BCSCL = @BCSCL,";
            strSql += "SCCL = @SCCL,";
            strSql += "NJGCSB = @NJGCSB,";
            strSql += "Other = @Other,";
            strSql += "Remark = @Remark";
            strSql += " where ReportId = @ReportId";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    int result = dbCon.Execute(strSql, model);
                    if (result > 0)
                    {
                        obj.model = result;
                        obj.status = DefaultKey.SuccessResult;
                        obj.message = "更新成功！";
                    }
                    else
                    {
                        obj.model = result;
                        obj.status = DefaultKey.InfoResult;
                        obj.message = "更新失败！数量为:" + result;
                    }
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("更新表11茧丝绸企业信息调查表MulSilkCompany对象信息失败", ex);
                return obj;
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        public ResResult<int> DeleteData(string id)
        {
            ResResult<int> obj = new ResResult<int>();
            string strSql = @"delete from dbo.MulSilkCompany where ReportId = @Id";
            int result;
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    result = dbCon.Execute(strSql, new { Id = id });
                    if (result > 0)
                    {
                        obj.model = result;
                        obj.status = DefaultKey.SuccessResult;
                        obj.message = "删除成功！";
                    }
                    else
                    {
                        obj.model = result;
                        obj.status = DefaultKey.InfoResult;
                        obj.message = "删除失败！数量为:" + result;
                    }
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("删除表11茧丝绸企业信息调查表MulSilkCompany对象信息失败", ex);
                return obj;
            }
        }


        /// <summary>
        /// 茧丝绸企业信息 统计   按年
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResResult<List<MulSilkCompanyModel>> GetMulSilkCompanyStatsList(MulNowModel model)
        {
            //string ProvinceCode = "530000000000";
            DictServices dictServices = new DictServices();
            if (!string.IsNullOrEmpty(model.FillInYear))
            {
                model.FillInYear = dictServices.GetPZKey(model.FillInYear, "ReportYear");
            }
            ResResult<List<MulSilkCompanyModel>> result = new ResResult<List<MulSilkCompanyModel>>();
            //统计代码
            string StrSql = "select c.* from  ";
            StrSql += " T_Report r inner join MulSilkCompany c on r.Id = c.ReportId left join T_Dict d on r.FillInYear=d.DictValue and d.GroupCode='ReportYear' ";
            StrSql += " where r.FillInYear = @FillInYear and r.Status=@ReportStatus ";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    var paramlist = new DynamicParameters();
                    // paramlist.Add("AreaCode", model.AreaCode);
                    paramlist.Add("FillInYear", model.FillInYear);
                    paramlist.Add("ReportStatus", model.Status);
                    List<MulSilkCompanyModel> listResult = new List<MulSilkCompanyModel>();
                    listResult = dbCon.Query<MulSilkCompanyModel>(StrSql, paramlist).ToList();
                    if (listResult != null)
                    {
                        result.model = listResult;
                        result.status = DefaultKey.SuccessResult;
                        result.message = "获取茧丝绸企业信息统计数据成功！";
                    }
                    else
                    {
                        result.status = DefaultKey.InfoResult;
                        result.message = "获取茧丝绸企业信息统计数据失败！";
                    }
                    dbCon.Dispose();//数据库连接释放
                }
            }
            catch (Exception ex)
            {
                result.status = DefaultKey.ErrorResult;
                result.message = ex.ToString().Trim();
                LogHelper.ErrorLog("获取茧丝绸企业信息统计数据失败", ex);
            }
            return result;
        }
    }
}